﻿using System.Text.RegularExpressions;

namespace Designit.Umbraco.Datatypes.VideoEmbed
{
    public class XsltExtension
    {
        public static string VideoEmbed(string url, int width, int height)
        {
            var youTubeUrl = new Regex(@"^http://(www\.)?youtube.com/watch\?v=(?<id>[0-9A-Za-z-_]{11})$*");
            var vimeoUrl = new Regex(@"^http://(?:www\.){0,1}vimeo\.com/(\d+)$*");
            var googleVideoUrl = new Regex(@"^http://?video.google.com/videoplay\?docid=(?<id>[0-9A-Za-z-_]{19})$*");

            if (youTubeUrl.IsMatch(url))
            {
                var urlNew = "http://www.youtube.com/v/" + youTubeUrl.Replace(url, @"${id}");
                return VideoEmbedParameters(urlNew, width, height);
            }

            if (vimeoUrl.IsMatch(url))
            {
                var urlNew = "http://vimeo.com/moogaloop.swf?clip_id=" + vimeoUrl.Replace(url, @"$1");
                return VideoEmbedParameters(urlNew, width, height);
            }

            if (googleVideoUrl.IsMatch(url))
            {
                var urlNew = "http://video.google.com/googleplayer.swf?docId=" + googleVideoUrl.Replace(url, @"$1");
                return VideoEmbedParameters(urlNew, width, height);
            }

            return "<b>ERROR:</b> video format not supported";
        }


        private static string VideoEmbedParameters(string url, int width, int height)
        {
            return "<object width=\"" + width + "\" height=\"" + height + "\"><param name=\"movie\" value=\"" + url +
          "\"></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowscriptaccess\" value=\"always\"></param><embed src=\"" +
          url + "\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\"" +
          width + "\" height=\"" + height + "\"></embed></object>";
        }

        private static string GetYouTubeVideoId(string url)
        {
            var testYouTubeUrl = new Regex(@"(\?v=)(\w[\w|-]*)");
            if (testYouTubeUrl.IsMatch(url))
            {
                foreach (Match tempMatch in testYouTubeUrl.Matches(url))
                    return (tempMatch.Value.Substring(3, tempMatch.Value.Length - 3));
            }
            return string.Empty;
        }
    }
}
